//
//  VCOfPlay.m
//  XYFMApp
//
//  Created by 岁变 on 16/9/3.
//  Copyright © 2016年 岁变. All rights reserved.
//

#import "VCOfPlay.h"
#import "XYMacro.h"

@interface VCOfPlay () <UIGestureRecognizerDelegate, XYPlayToolDelegate, UMSocialUIDelegate>
@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, strong) UIImageView *picImageView;
@property (nonatomic, strong) UIButton *buttonList;
@property (nonatomic, strong) UIButton *buttomCollect;
@property (nonatomic, strong) UIButton *buttonGood;
@property (nonatomic, strong) UIButton *buttonDownload;
@property (nonatomic, strong) UISlider *mySlider;
@property (nonatomic, strong) UIImageView *lastOneImageView;
@property (nonatomic, strong) UIImageView *nextOneImageView;
@property (nonatomic, strong) UIButton *playButton;
@property (nonatomic, strong) UIImageView *imageViewOne;
@property (nonatomic, strong) UIImageView *imageViewTwo;
@property (nonatomic, strong) UIView *myView;
@property (nonatomic, strong) UIImageView *promptView;
@property (nonatomic, strong) UIButton *shareButton;
@property (nonatomic, strong) UIButton *jubaoButton;

@property (nonatomic, strong) UILabel *totleTimeLabel;
@property (nonatomic, strong) UILabel *currentTimeLabel;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) CGFloat progress;
@property (nonatomic, strong) NSString *oldURL;
@property (nonatomic, strong) UILabel *proLabel;
@property (nonatomic, strong) NSString *proStr;

@property (nonatomic, strong) NSUserDefaults *user;
@property (nonatomic, strong) NSString *uid;

@property (nonatomic, strong) PlayVCModelOfCollect *collectModel;

@end

static VCOfPlay *playVC = nil;

@implementation VCOfPlay

//单例方法
+ (instancetype)sharePlayVC {
    if (playVC == nil) {
        
        static dispatch_once_t once_token;
        dispatch_once(&once_token, ^{
            
            playVC = [[VCOfPlay alloc] init];
        });
    }
    return playVC;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self configNavigationController];
    [self createPlayer];
    [self configViewController];
    [self createSharePromptView];
}

- (void)createPlayer {
    _player = [XYPlayTools shareMyPlayer];
    _player.delegate = self;
}

#pragma mark ----XYPlayToolDelegate ------------

- (void)getCurrentTime:(NSString *)curTime totleTime:(NSString *)totleTime progress:(CGFloat)progress {
    
    _totleTimeLabel.text = totleTime;
    _currentTimeLabel.text = curTime;
    _progress = progress;
    
}

- (void)endOfPlayAction {
    NSLog(@"播放结束");
    
}





- (void)configNavigationController {
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    UIButton *goBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackButton.frame = CGRectMake(0, 0, 30, 30);
    [goBackButton setImage:[UIImage imageNamed:@"go_back"] forState:UIControlStateNormal];
    [goBackButton addTarget:self action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:goBackButton];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIButton *shareBautton = [UIButton buttonWithType:UIButtonTypeCustom];
    shareBautton.frame = CGRectMake(0, 0, 30, 30);
    [shareBautton setImage:[UIImage imageNamed:@"Unknown"] forState:UIControlStateNormal];
    [shareBautton addTarget:self action:@selector(clickShareButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:shareBautton];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)clickShareButton:(UIButton *)button {
    button.selected = !button.selected;
    if (button.selected) {
        _promptView.hidden = NO;
    } else {
        _promptView.hidden = YES;
    }
    
}

- (void)createSharePromptView {
    _promptView = [UIImageView new];
    _promptView.image = [UIImage imageNamed:@"near_filter_bg"];
    _promptView.frame = CGRectMake(SCREEN_WIDTH - 170, 0, 150, 120);
    [_backImageView addSubview:_promptView];
    _promptView.userInteractionEnabled = YES;
    _promptView.hidden = YES;
    
    _shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_shareButton setTitle:@"分享" forState:UIControlStateNormal];
    [_shareButton addTarget:self action:@selector(shareWith:) forControlEvents:UIControlEventTouchUpInside];
    [_shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _shareButton.frame = CGRectMake(0, 15, _promptView.frame.size.width, _promptView.frame.size.height / 2 - 20);
    [_promptView addSubview:_shareButton];
    
    _jubaoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_jubaoButton setTitle:@"举报" forState:UIControlStateNormal];
    [_jubaoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _jubaoButton.frame = CGRectMake(0, _promptView.frame.size.height / 2 + 15, _promptView.frame.size.width, _promptView.frame.size.height / 2 - 20);
    [_promptView addSubview:_jubaoButton];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, _promptView.frame.size.height / 2 , _promptView.frame.size.width, 2)];
    lineView.backgroundColor = [UIColor colorWithRed:0.38 green:0.40 blue:0.45 alpha:1.00];
    [_promptView addSubview:lineView];
    
}


#pragma mark ------收藏功能----------------
- (void)sendcollectMessgae {
    
    NSString *str1 = @"json=%7B%22session%22%3A%7B%22uid%22%3A%22";
    NSString *str2 = @"%22%2C%22sid%22%3A%22c4aca220e2b147afb71fcf2980ea755d%22%7D%2C%22content_ids%22%3A%22";
    NSString *str3 = @"%22%2C%22operate%22%3A1%7D";
    NSString *body = [[[[str1 stringByAppendingString:_uid] stringByAppendingString:str2] stringByAppendingString:_content_id] stringByAppendingString:str3];
    
    [XYNetWorkParser POST:@"http://www.aiyinsitanfm.com/mobile/content/proccollect.jhtml" andBody:body andBodyStyle:XYBodyString andHeader:URLHEADER andResponse:XYJSON andSuccessBlock:^(id result) {
        
       _collectModel = [PlayVCModelOfCollect modelWithDictionary:result];
        NSLog(@"%@", _collectModel.proclist);

        if (_collectModel.status.succeed == 1 && _collectModel.proclist.length != 0) {
            _proStr = @"收藏成功";
            [self createPromptBox];
        }
        if (_collectModel.status.succeed == 1 && _collectModel.proclist.length == 0) {
            _proStr = @"已经收藏";
            [self createPromptBox];
        }
        
    } andFailureBlock:^(NSError *error) {}];

    
}


//分享
- (void)shareWith:(UIButton *)button {
    _promptView.hidden = YES;
    
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"57ddefde67e58ee7c8002fcb" shareText:@"你要分享的文字:" shareImage:[UIImage imageNamed:@"icon.png"] shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQzone,UMShareToQQ,UMShareToRenren,UMShareToDouban,UMShareToEmail,UMShareToSms,UMShareToFacebook,UMShareToTwitter, nil ] delegate:self];
    NSLog(@"分享");
}


- (void)configViewController {
    
    _backImageView = [[UIImageView alloc] init];
    _backImageView.userInteractionEnabled = YES;
    _backImageView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64);
    [self.view addSubview:_backImageView];
    
    UIView *backgroundView = [[UIView alloc] initWithFrame:_backImageView.bounds];
    backgroundView.backgroundColor = [UIColor blackColor];
    backgroundView.alpha = 0.5;
    [_backImageView addSubview:backgroundView];
    
    
    _picImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"playbar"]];
    _picImageView.frame = CGRectMake(0, _backImageView.frame.size.height - 370, 160, 330);
    _picImageView.userInteractionEnabled = YES;
    [_backImageView addSubview:_picImageView];
    
    _lastOneImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"before"]];
    _lastOneImageView.frame = CGRectMake(45, 30, 20, 30);
    [_picImageView addSubview:_lastOneImageView];
    
    //添加上一曲手势
    UITapGestureRecognizer *tapOfLast = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastOne:)];
    tapOfLast.numberOfTapsRequired = 1;
    tapOfLast.numberOfTouchesRequired = 1;
    tapOfLast.delegate = self;
    [_lastOneImageView addGestureRecognizer:tapOfLast];
    _lastOneImageView.userInteractionEnabled = YES;
    
    
    _nextOneImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"next"]];
    _nextOneImageView.frame = CGRectMake(45, 145, 20, 30);
    [_picImageView addSubview:_nextOneImageView];
    
    //添加下一曲手势
    UITapGestureRecognizer *tapOfNext = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(nextOne:)];
    tapOfNext.numberOfTapsRequired = 1;
    tapOfNext.numberOfTouchesRequired = 1;
    tapOfNext.delegate = self;
    [_nextOneImageView addGestureRecognizer:tapOfNext];
    _nextOneImageView.userInteractionEnabled = YES;
     
    _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playButton.frame = CGRectMake(43, 87, 20, 30);
    [_playButton addTarget:self action:@selector(clickPlayButton:) forControlEvents:UIControlEventTouchUpInside];
    [_picImageView addSubview:_playButton];
    
    _imageViewOne = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"AA"]];
    _imageViewOne.frame = CGRectMake(170, _backImageView.frame.size.height - 310, _backImageView.frame.size.width - 170, 80);
    _imageViewOne.userInteractionEnabled = YES;
    [_backImageView addSubview:_imageViewOne];
    
    _imageViewTwo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BB"]];
    _imageViewTwo.frame = self.imageViewOne.bounds;
    _imageViewTwo.userInteractionEnabled = YES;
    _myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 80)];
    _myView.clipsToBounds = YES;
    [_imageViewOne addSubview:_myView];
    [_myView addSubview:_imageViewTwo];
    
    _mySlider = [[UISlider alloc] initWithFrame:CGRectMake(0, 20, _backImageView.frame.size.width - 170, 60)];
    [_mySlider setThumbImage:[UIImage imageNamed:@"ball"] forState:UIControlStateNormal];
    [_mySlider setMaximumTrackTintColor:[UIColor whiteColor]];
    [_mySlider setMinimumTrackTintColor:[UIColor redColor]];
    [_mySlider addTarget:self action:@selector(changTime:) forControlEvents:UIControlEventValueChanged];
    _mySlider.maximumValue = _imageViewOne.frame.size.width;
    [_imageViewOne addSubview:_mySlider];
    
    UIView *viewOne = [[UIView alloc] initWithFrame:CGRectMake(70, _backImageView.frame.size.height - 80, _backImageView.frame.size.width - 80, 3)];
    viewOne.backgroundColor = [UIColor colorWithRed:0.38 green:0.40 blue:0.45 alpha:1.00];
    [_backImageView addSubview:viewOne];
    
    UIView *viewTwo = [[UIView alloc] initWithFrame:CGRectMake(120, _backImageView.frame.size.height - 100, 3, 10)];
    viewTwo.backgroundColor = [UIColor colorWithRed:0.38 green:0.40 blue:0.45 alpha:1.00];
    [_backImageView addSubview:viewTwo];
    
    _buttonList = [UIButton buttonWithType:UIButtonTypeCustom];
    [_buttonList setImage:[UIImage imageNamed:@"player_menu_list"] forState:UIControlStateNormal];
    _buttonList.frame = CGRectMake(95, _backImageView.frame.size.height - 160 , 53, 53);
    [_buttonList addTarget:self action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];
    [_backImageView addSubview:_buttonList];
    
    UIView *viewThree = [[UIView alloc] initWithFrame:CGRectMake(200, _backImageView.frame.size.height - 130, 3, 30)];
    viewThree.backgroundColor = [UIColor colorWithRed:0.38 green:0.40 blue:0.45 alpha:1.00];
    [_backImageView addSubview:viewThree];
    
    _buttomCollect = [UIButton buttonWithType:UIButtonTypeCustom];
    [_buttomCollect setImage:[UIImage imageNamed:@"player_menu_save_0"] forState:UIControlStateNormal];
    _buttomCollect.frame = CGRectMake(175, _backImageView.frame.size.height - 190, 53, 53);
    [_buttomCollect addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
    [_backImageView addSubview:_buttomCollect];
    
    UIView *viewFour = [[UIView alloc] initWithFrame:CGRectMake(280, _backImageView.frame.size.height - 100, 3, 10)];
    viewFour.backgroundColor = [UIColor colorWithRed:0.38 green:0.40 blue:0.45 alpha:1.00];
    [_backImageView addSubview:viewFour];
    
    _buttonGood = [UIButton buttonWithType:UIButtonTypeCustom];
    [_buttonGood setImage:[UIImage imageNamed:@"player_menu_zan_0"] forState:UIControlStateNormal];
    _buttonGood.frame = CGRectMake(255, _backImageView.frame.size.height - 160 , 53, 53);
    [_backImageView addSubview:_buttonGood];
    
    UIView *viewFive = [[UIView alloc] initWithFrame:CGRectMake(360, _backImageView.frame.size.height - 130, 3, 30)];
    viewFive.backgroundColor = [UIColor colorWithRed:0.38 green:0.40 blue:0.45 alpha:1.00];
    [_backImageView addSubview:viewFive];
    
    _buttonDownload = [UIButton buttonWithType:UIButtonTypeCustom];
    [_buttonDownload setImage:[UIImage imageNamed:@"player_menu_down_0"] forState:UIControlStateNormal];
    _buttonDownload.frame =  CGRectMake(335, _backImageView.frame.size.height - 190, 53, 53);
    [_buttonDownload addTarget:self action:@selector(downloadAction:) forControlEvents:UIControlEventTouchUpInside];
    [_backImageView addSubview:_buttonDownload];
    
    _currentTimeLabel = [[UILabel alloc] init];
    _currentTimeLabel.text = @"00:00";
    _currentTimeLabel.textColor = [UIColor redColor];
    _currentTimeLabel.frame = CGRectMake(90, 75, 60, 30);
    [_picImageView addSubview:_currentTimeLabel];
    
    _totleTimeLabel = [[UILabel alloc] init];
    _totleTimeLabel.text = @"00:00";
    _totleTimeLabel.textColor = [UIColor lightGrayColor];
    _totleTimeLabel.frame = CGRectMake(90, 105, 50, 20);
    _totleTimeLabel.font = [UIFont systemFontOfSize:15];
    [_picImageView addSubview:_totleTimeLabel];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(changeValue:) userInfo:nil repeats:YES];
}


#pragma mark -----------创建自定义提示栏-----------------
- (void)createPromptBox {
    UIWindow *windows = [UIApplication sharedApplication].keyWindow;
    UIView *customPromptBox = [[UIView alloc]init];
    customPromptBox.backgroundColor = BACKGROUNDCOLOR;
    customPromptBox.frame = CGRectMake(0, 0, 200, 50);
    customPromptBox.center = windows.center;
    customPromptBox.clipsToBounds = YES;
    customPromptBox.layer.cornerRadius = 5;
    customPromptBox.layer.borderWidth = 2;
    customPromptBox.layer.borderColor = [UIColor redColor].CGColor;
    
    _proLabel = [[UILabel alloc] init];
    _proLabel.textAlignment = NSTextAlignmentCenter;
    _proLabel.backgroundColor = BACKGROUNDCOLOR;
    _proLabel.textColor = [UIColor whiteColor];
    _proLabel.text = _proStr;
    _proLabel.frame = CGRectMake(10, 0, customPromptBox.frame.size.width - 20, 50);
    [customPromptBox addSubview:_proLabel];
    [windows addSubview:customPromptBox];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
        //2秒以后移除view
        [customPromptBox removeFromSuperview];
    });
}



- (void)changTime:(UISlider *)slider {
    _myView.frame = CGRectMake(0, 0, slider.value, 80);
    [_player seekToTimeWithValue:(slider.value / _imageViewOne.frame.size.width)];
}

- (void)changeValue:(NSTimer *)timer {
    
    _mySlider.value = _imageViewOne.frame.size.width * _progress;
    _myView.frame = CGRectMake(0, 0, _mySlider.value, 80);
}


//- (void)play:(UIButton *)button {
//    
//    //[_playButton setImage:[UIImage imageNamed:@"pause_img"] forState:UIControlStateNormal];
//    [_playButton removeTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
//    [_playButton addTarget:self action:@selector(pasue:) forControlEvents:UIControlEventTouchUpInside];
//    [self.player musicPlay];
//}

- (void)clickPlayButton:(UIButton *)button {
//    [_playButton setImage:[UIImage imageNamed:@"play_img"] forState:UIControlStateNormal];
//    [_playButton removeTarget:self action:@selector(pasue:) forControlEvents:UIControlEventTouchUpInside];
//    [_playButton addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
    //暂停播放
    if (_player.myPlayer.rate == 0) {
        [self.player musicPlay];
    } else if (_player.myPlayer.rate == 1) {
        [self.player musicPause];
    }
}

- (void)nextOne:(UITapGestureRecognizer *)nextTap {
    
    if (_index == (_mp3URLArr.count - 1)) {
        _proStr = @"没有更多了";
        [self createPromptBox];
    } else {
        _index += 1;
        _player.mp3URL = [_mp3URLArr objectAtIndex:_index];

        [_player musciPreparePlay];
    }
}

- (void)lastOne:(UITapGestureRecognizer *)lastTap {
    
    if (_index == 0) {
        _proStr = @"当前为第一首";
        [self createPromptBox];
    } else {
        _index -= 1;
        _player.mp3URL = [_mp3URLArr objectAtIndex:_index];
        [_player musciPreparePlay];
    }
}



- (void)goBack:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
    if ([[self.navigationController.viewControllers lastObject] isKindOfClass:[VCOfLoveListen class]]) {
        self.tabBarController.tabBar.hidden = NO;
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.94 green:0.00 blue:0.00 alpha:1.00];
    } else {
        self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    }
}

- (void)collectAction:(UIButton *)button {
    
    if (![_user objectForKey:@"password"]) {
        _proStr = @"尚未登录,请先登录";
        [self createPromptBox];
    } else {
        
        [self sendcollectMessgae];
        
    }
    
}

- (void)downloadAction:(UIButton *)button {
    _proStr = @"暂未提供下载功能";
    [self createPromptBox];
}


- (void)viewWillAppear:(BOOL)animated {
    
    self.title = _titleStr;
    
    [_backImageView sd_setImageWithURL:[NSURL URLWithString:_imagePicURL]];

    
    _player.mp3URL = _mp3URL;
    if ([_mp3URL isEqualToString:_oldURL]) {
        return;
    }

    _player = [XYPlayTools shareMyPlayer];
    [_player musciPreparePlay];
    _oldURL = _mp3URL;
    
    
    //添加观察者
    [_player.myPlayer addObserver:self forKeyPath:@"rate" options:NSKeyValueObservingOptionNew context:nil];

    
    //[_playButton setImage:[UIImage imageNamed:@"pause_img"] forState:UIControlStateNormal];
    
    
    
    _user = [NSUserDefaults standardUserDefaults];
    
    if ([_user objectForKey:@"password"]) {
        _uid = [_user objectForKey:@"target_id"];
    }
    
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    NSString *str = [NSString stringWithFormat:@"%@", [change objectForKey:@"new"]];
    if ([str isEqualToString:@"0"] ) {
        [_playButton setImage:[UIImage imageNamed:@"play_img"] forState:UIControlStateNormal];
    }
    if ([str isEqualToString:@"1"]) {
        [_playButton setImage:[UIImage imageNamed:@"pause_img"] forState:UIControlStateNormal];
    }
}


- (void)dealloc {
    [_player.myPlayer removeObserver:self forKeyPath:@"status"];
}



- (void)viewDidAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;
}

- (void)setMp3URLArr:(NSMutableArray *)mp3URLArr {
    _mp3URLArr = [NSMutableArray array];
    _mp3URLArr = mp3URLArr;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
